package com.example.blogback.controller;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.blogback.common.Result;
import com.example.blogback.entity.Blog;
import com.example.blogback.service.BlogService;
import com.example.blogback.utils.ShiroUtil;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author JHL
 * @since 2022-04-22
 */
@RestController
public class BlogController {


    @Autowired
    BlogService blogService;

    @GetMapping("/blogs")
    public Result list(@RequestParam(defaultValue = "1") Integer currentPage){

        Page page = new Page(currentPage,5);
        IPage pageData = blogService.page(page, new QueryWrapper<Blog>().orderByDesc("created"));

        return Result.success(pageData);

    }

    @GetMapping("/blog/{id}")
    public Result detail(@PathVariable(name = "id") Long id){
        Blog blog = blogService.getById(id);
        Assert.notNull(blog,"博客已被删除");
        return Result.success(blog);
    }

    @RequiresAuthentication
    @PostMapping("/blog/edit")
    public Result edit(@Validated @RequestBody Blog blog){
        Blog temp=null;
        if(blog.getId()!=null){
            temp=blogService.getById(blog.getId());
            System.out.println("当前edit的用户ID="+ShiroUtil.getProfile().getId());
            boolean res = blogService.updateById(blog);
            if(res) System.out.println("编辑博客成功");
            Assert.isTrue(temp.getUserId().longValue()== ShiroUtil.getProfile().getId().longValue(),
                    "没有权限编辑");
        } else {
            System.out.println("新建博客");

            temp = new Blog();
            temp.setUserId(ShiroUtil.getProfile().getId());
            temp.setCreated(LocalDateTime.now());
            temp.setStatus(0);
            temp.setTitle(blog.getTitle());
            temp.setDescription(blog.getDescription());
            temp.setContent(blog.getContent());
            blogService.save(temp);
        }
        BeanUtil.copyProperties(blog,temp,"id","userId","created","status");
        return Result.success(null);
    }





}
